# coding=utf-8
__author__ = 'liubin'

import os
from flask import url_for, json
from flask.ext.admin import form
from flask.ext.restful import Resource, fields, marshal, reqparse
from project import app, db, Item, admin_view, api_view
from project.admin import ImageView


class ItemListApi(Resource):
    """
    restful访问方式
    需要定义可以解析的结构
    """

    #对于 Item的结构定义的restful映射对象
    _resource_fields = {
        'id': fields.String,
        'name': fields.String,
        'description': fields.String,
        'price': fields.Price(decimals=2),
        'image': fields.String,
        'store_id': fields.String
    }

    def get(self, **kwargs):
        """
        restful的get方法
        :param kwargs:
        :return:
        """

        #请求参数的解析
        parser = reqparse.RequestParser()

        #sencha touch 前台的过滤用filter 传过来
        parser.add_argument('filter', type=str)
        args = parser.parse_args()
        print(args)
        #store id 作为查询参数
        store_id = None
        if args['filter'] is not None:
            filters = json.loads(args['filter'])
            for filter in filters:
                if filter.get('property', '') == 'store_id':
                    store_id = filter.get('value')
        query = Item.query
        if store_id is not None:
            query = query.filter_by(store_id=store_id)
        data = []
        for item in query.all():
            item_image = os.path.join(app.config['UPLOAD_DIRECTORY'], item.image).replace('\\', '/')
            data_item = {
                'id': item.id,
                'name': item.name,
                'description': item.description,
                'price': item.price,
                'image': url_for('static', filename=form.thumbgen_filename(item_image)),
                'store_id': item.store_id
            }

            # marshal用来映射 restful 对象
            data.append(marshal(data_item, self._resource_fields))

        #加上处理状态
        return {'success': True,  'data': data}

# 映射restful的url
api_view.add_resource(ItemListApi, '/api/item')
# Store Admin视图
admin_view.add_view(ImageView(Item, db.session))